package com.eva.framework.config;

import com.eva.framework.cache.CacheProxy;
import com.eva.framework.common.constants.CacheKeys;
import com.eva.framework.common.utils.Utils;
import com.eva.framework.config.model.SystemConfigCache;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

/**
 * 系统配置帮助类
 * 用于方便获取应用的系统配置
 */
@Component
public class SystemConfigHelper {

    private CacheProxy<String, Map<String, SystemConfigCache>> cacheProxy;

    private String appId;

    private SystemConfigHelper () {
    }

    /**
     * 构建实例
     *
     * @param appId 应用ID
     * @return SystemConfigHelper
     */
    public static SystemConfigHelper build (String appId) {
        SystemConfigHelper helper = new SystemConfigHelper();
        helper.appId = appId;
        helper.cacheProxy = Utils.SpringContext.getBean(CacheProxy.class);
        return helper;
    }

    /**
     * 获取系统配置内容
     *
     * @param configCode 配置编码
     * @return 配置值
     */
    public String get (String configCode) {
        SystemConfigCache cache = cacheProxy
                .get(this.getCacheKey())
                .get(configCode);
        if (cache == null) {
            return null;
        }
        return cache.getValue();
    }

    /**
     * 获取系统配置列表
     *
     * @return Collection<SystemConfigCache>
     */
    public Collection<SystemConfigCache> getList() {
        return cacheProxy.get(this.getCacheKey()).values();
    }

    /**
     * 获取系统配置列表
     *
     * @return Collection<SystemConfigCache>
     */
    public Map<String, SystemConfigCache> getMap() {
        return cacheProxy.get(this.getCacheKey());
    }

    /**
     * 获取缓存键，格式：{应用ID}_{CacheKeys.SYSTEM_CONFIGS}
     * @return String
     */
    public String getCacheKey () {
        return this.appId + "_" + CacheKeys.SYSTEM_CONFIGS;
    }
}
